package manager

import android.content.Context
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import app.AppContext
import mvc.model.Status
import task.StatusChangedUploadTask

object StatusManager : PhoneStateListener() {

    private val mTelephonyManager = AppContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    var Signal = 0
    var StatusCount = 0

    var status = Status.withNormal()

    init {
        mTelephonyManager.listen(this, LISTEN_SIGNAL_STRENGTHS)
    }

    fun refresh(s: Status) {
        StatusCount++
        if (s != status) {
            TaskManager.DelayHandler.postDelayed(StatusChangedUploadTask(), 500)
        }
        status = s
    }

    override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
        val tmp = signalStrength.toString()
        val parts = tmp.split(" ")
        val dbm = parts[1].toInt() * 2 - 113
        if (mTelephonyManager.networkType == TelephonyManager.NETWORK_TYPE_LTE) {
            if (dbm > 0) {
                Signal = 0
            } else if (dbm > -60) {
                Signal = 4
            } else if (dbm > -75) {
                Signal = 3
            } else if (dbm > -80) {
                Signal = 2
            } else if (dbm > -90) {
                Signal = 1
            }
        } else {
            Signal = 0
        }
        super.onSignalStrengthsChanged(signalStrength)
    }
}